package com.rzt.cft.service.sys.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rzt.cft.utils.CustomUtil;
import com.rzt.cft.entity.sys.SysMenu;
import com.rzt.cft.entity.sys.SysRole;
import com.rzt.cft.entity.sys.SysRoleMenu;
import com.rzt.cft.mapper.sys.SysRoleMapper;
import com.rzt.cft.mapper.sys.SysRoleMenuMapper;
import com.rzt.cft.service.sys.ISysRoleMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 系统-后台角色功能 服务实现类
 * </p>
 *
 * @author zhongzhong
 * @since 2019-12-31
 */
@Service
public class SysRoleMenuServiceImpl extends ServiceImpl<SysRoleMenuMapper, SysRoleMenu> implements ISysRoleMenuService {

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysRoleMenuMapper sysRoleMenuMapper;

    @Override
    public Boolean allotRoleMenu(String roleId, List<SysMenu> menuListList) {

        SysRole role = sysRoleMapper.selectById(roleId);
        if (Objects.isNull(role))
            return false;

        List<SysRoleMenu> dbItemList = CustomUtil.maping(menuListList, SysRoleMenu.class);
        dbItemList.forEach(x -> {
            x.setRoleId(roleId);
            x.setMenuId(x.getId());
        });

        // 当前菜单功能标识集合
        List<String> menuIdList = CustomUtil.select(menuListList, SysMenu::getId);

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("role_id", roleId);
        // 原有分配项
        List<SysRoleMenu> oldList = sysRoleMenuMapper.selectList(queryWrapper);

        // 已有功能标识集合
        List<String> oidList = CustomUtil.select(oldList, SysRoleMenu::getMenuId);

        // 新增项
        List<SysRoleMenu> newList = CustomUtil.where(dbItemList, x -> !oidList.contains(x.getMenuId()));
        // 删除项
        List<SysRoleMenu> delList = CustomUtil.where(oldList, x -> !menuIdList.contains(x.getMenuId()));
        List<String> didList = CustomUtil.select(delList, SysRoleMenu::getId);
        if (delList.size() > 0) {
            sysRoleMenuMapper.deleteBatchIds(didList);
        }
        if (newList.size() > 0) {
            newList.forEach( x -> {
                sysRoleMenuMapper.insert(x);
            });
        }
        return true;
    }
}
